<template>
	<view class="apply-partner-wrapper">
		<!-- 返回首页 -->
		<uni-bankhome />
		<view class='form-wrapper'>
			<u-form :model="ruleForm" label-width="160rpx" ref="uForm">
				<u-form-item required label="电话" prop="phone">
					<div class="form-item">
						<u-input class="input" v-model="ruleForm.phone" placeholder="请输入电话" />
					</div>
				</u-form-item>
				<u-form-item required label="身份证" prop="idCard">
					<div class="form-item" @click="chooseImage()">
						<u-input @click.stop="chooseImage()" class="input" disabled v-model="ruleForm.idCard"
							placeholder="请识别身份证号" />
						<u-icon @click.stop="chooseImage()" name="camera-fill" size="32"></u-icon>
					</div>
				</u-form-item>
				<u-form-item required label="姓名" prop="name">
					<div class="form-item">
						<u-input class="input" disabled v-model="ruleForm.name" placeholder="请识别身份证姓名" />
					</div>
				</u-form-item>
				<u-form-item required label="居住区域" prop="storeAddressPath_path">
					<div class="form-item" @click.stop="openMap">
						<u-input @click.stop="openMap" class="input" disabled v-model="ruleForm.storeAddressPath_path"
							placeholder="选择位置" />
						<u-icon @click.stop="openMap" name="arrow-right" size="32"></u-icon>
					</div>
				</u-form-item>
				<u-form-item label-width="220rpx" required label="是否有推荐人">
					<u-radio-group v-model="tjrState">
						<u-radio v-for="(item, index) in tjrList" :key="index" :name="item.name"
							:disabled="item.disabled">
							{{ item.name }}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item v-if="tjrState==='有'" required label="手机号" prop="tjrPhone">
					<div class="form-item">
						<u-input class="input" v-model="ruleForm.tjrPhone" placeholder="请输入推荐人手机号" />
					</div>
				</u-form-item>
				<u-form-item required label="端口费" prop="fee">
					<div class="form-item">
						<u-input class="input" disabled v-model="ruleForm.fee" placeholder="请获取端口费" />
					</div>
				</u-form-item>
			</u-form>
			<view class="customBtn">
				<u-button
					:customStyle="{'background':'linear-gradient(162.65deg, rgba(255, 98, 0, 1) 0%, rgba(240, 139, 67, 0.65) 100%)','color':'#fff','border-radius': '23px' }"
					@click="submit">立即支付</u-button>
			</view>
		</view>
		<p-city class="address-position" :provinceData="list" headTitle="区域选择" ref="pcityPicker"
			@funcValue="getpickerParentValue" pickerSize="3">
		</p-city>
		<m-city class="address-position" :provinceData="list" headTitle="区域选择" ref="mcityPicker"
			@funcValue="getpickerParentValue" pickerSize="3">
		</m-city>
		<uniMap v-if="mapFlage" @close="closeMap" @callback="callBackAddress" />
		<pay-methods finish="refresh" type="RECHARGE" @payFinish="payFinish" ref="payMethods" zero="1"></pay-methods>
	</view>
</template>
<script>
	import storage from "@/utils/storage.js";
	import {
		getaddPartner,
		getCertificateIdentification,
		partnerPrice
	} from "@/api/goods";
	import api from "@/config/api.js";
	import uniMap from "@/components/map/map.vue";
	import BigNumber from 'bignumber.js'
	import payMethods from "@/components/pay-methods/pay-methods.vue"
	import pCity from '@/components/p-city/m-city.vue'
	import mCity from '@/components/m-city/m-city.vue'
	export default {
		data() {
			return {
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}],
				action: '',
				tjrList: [{
						name: '有',
						disabled: false
					},
					{
						name: '无',
						disabled: false
					}
				],
				tjrState: '无',
				ruleForm: {
					phone: '',
					idCard: '',
					name: '',
					storeAddressPath_path: '',
					tjrPhone: '',
					fee: ''
				},
				rules: {
					phone: [{
							required: true,
							message: "电话不能为空",
							trigger: ["blur", "change"],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: "电话号码格式不正确",
							trigger: ["change", "blur"],
						},
					],
					idCard: [{
						required: true,
						message: "请识别身份证",
						trigger: ["blur", "change"],
					}],
					name: [{
						required: true,
						message: "请识别身份证",
						trigger: ["blur", "change"],
					}],
					storeAddressPath_path: [{
						required: true,
						message: "请选择位置-区域",
						trigger: ["blur", "change"],
					}],
					tjrPhone: [{
						validator: (rule, value, callback) => {
							if (this.tjrState === '有') {
								return this.$u.test.mobile(value);
							} else {
								return true
							}
						},
						message: "推荐人号码格式不正确",
						trigger: ["change", "blur"],
					}],
					fee: [{
						required: true,
						message: "请获取端口费",
						trigger: ["blur", "change"],
					}]
				},
				mapFlage: false, // 地图是否打开
			};
		},
		components: {
			uniMap,
			payMethods,
			pCity,
			mCity
		},
		onLoad(option) {
			this.$options.filters.forceLogin()
			if (option.partner == 'sy') {
				this.setTitle('事业合伙人', 'sy')
				this.ruleForm.partnerType = '1'
			} else if (option.partner == 'ts') {
				this.setTitle('天使合伙人', 'ts')
				this.ruleForm.partnerType = '2'
			} else if (option.partner == 'cs') {
				this.setTitle('城市合伙人', 'cs')
				this.ruleForm.partnerType = '4'
			}
			this.initHL()
		},
		onShow() {},
		methods: {
			//设置title 获取端口费用
			setTitle(title, tag) {
				uni.setNavigationBarTitle({
					title
				})
				// 请求接口，获取端口费用
				this.partnerPrice(tag)
			},
			//获取端口费用
			partnerPrice(type) {
				partnerPrice({
					type
				}).then((res) => {
					if (res.data.code === 200) {
						this.ruleForm.fee = res.data.result.itemValue
					} else {
						this.toast(res.data.message)
					}
				}).catch(err => {
					this.toast(err)
				})
			},
			// 打开地图
			openMap() {
				if (this.ruleForm.partnerType == '4') {
					this.$refs.pcityPicker.show()
				} else {
					this.$refs.mcityPicker.show()
				}
			},
			// 关闭地图
			closeMap() {
				this.mapFlage = false;
			},
			// 选址回调
			callBackAddress(val) {
				let addressData = {}
				uni.showLoading({
					title: "加载中",
				});
				console.log("@#@#@##", val)
				if (val.regeocodeData && val) {
					addressData.area = val.data.result.name;
					if (addressData.area) {
						addressData.area = addressData.area.split(',').join('')
						addressData.adCode = val.regeocodeData.addressComponent.adcode
					}
					this.ruleForm.storeAddressPath_path = addressData.area
					this.ruleForm.adPath = addressData.adCode
					uni.hideLoading();
				}
				this.closeMap() //关闭地图
			},
			// 三级地址联动回调
			getpickerParentValue(e) {
				let list = e.filter((item) => {
					return !!item.id
				})
				let path = []
				list.forEach((item, index) => {
					if (item.id) {
						path.push(item.localName);
					}
				});
				this.ruleForm.storeAddressPath_path = path.join('')
				this.ruleForm.adPath = list[list.length - 1].adCode
			},
			// 身份证上传以及信息识别
			chooseImage() {
				let Token = storage.getAccessToken()
				let that = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						var tempFilePaths = res.tempFilePaths
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: api.common + '/upload/file',
								fileType: "image",
								filePath: tempFilePaths[i],
								name: 'file',
								ruleForm: {},
								'content-type': 'multipart/form-data',
								header: {
									accessToken: Token,
									'content-type': 'multipart/form-data' // 设置请求的 header
								},
								success: function(res) {
									res = JSON.parse(res.data)
									if (res.code == 200) {
										let imgUrl = res.result
										that.distinguish(imgUrl)
									} else {
										this.toast(res.message)
									}
								}
							})
						}
					}
				})
			},
			// 证件识别
			distinguish(url) {
				uni.showLoading({
					title: "识别中",
				});
				// 开始识别
				getCertificateIdentification({
					url,
				}).then((res) => {
					if (res.data.code === 200) {
						const data = JSON.parse(res.data.result);
						console.log(data);
						let {
							num,
							name
						} = data
						this.ruleForm.idCard = num
						this.ruleForm.name = name
						uni.hideLoading();
					} else {
						this.toast(res.data.message)
					}
				}).catch(err => {
					this.toast(err)
				})
			},
			//toast提示
			toast(txt) {
				uni.showToast({
					title: txt,
					duration: 1500,
					icon: "none",
				});
			},
			//提交信息
			submit() {
				this.$refs.uForm.validate((valid) => {
					console.log("@@@", this.ruleForm)
					if (valid) {
						let params = {
							rechargeType: 45,
							price: this.ruleForm.fee,
							hbPrice: this.ruleForm.fee,
							vipPrice: this.ruleForm.fee,
							...this.ruleForm
						}
						this.$refs.payMethods.payChoose('wechat', params)
					} else {
						uni.showToast({
							title: "请填写有效信息",
							duration: 2000,
							icon: "none",
						});
					}
				});
			},
			payFinish() {
				uni.showToast({
					title: "提交成功!",
					duration: 2000,
					icon: "none",
				});

				setTimeout(() => {
					uni.navigateBack();
					uni.reLaunch({
						url: '/pages/tabbar/user/my'
					})
				}, 500);
			},
			/**
			 * 初始化汇率、个人用户信息（会员身份）、店铺信息
			 * */
			initHL() {
				let rate = storage.getVipRate();
				this.vipRate = rate
				this.userInfo = this.$options.filters.isLogin();
				if (this.userInfo.gradeName && rate[this.userInfo.gradeName].rate) {
					this.rate = rate[this.userInfo.gradeName].rate
				} else {
					this.rate = rate['0'].rate
				}
				let userinfo = storage.getUserInfo()
				this.partnerType = userinfo.partnerType
				let businessState = storage.getBusiness()
				this.businessState = businessState
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
	};
</script>
<style lang="scss" scoped>
	.apply-partner-wrapper {
		.form-wrapper {
			padding: 0 32upx;
		}

		.form-item {
			background-color: #ffffff;
			padding: 0 24upx;
			border-radius: 8upx;
			display: flex;

			.input {
				flex: 1;
			}
		}

		.customBtn {
			width: calc(100% - 64upx);
			position: fixed;
			bottom: 10px;
			text-align: center;
		}
	}
</style>
